<template>
  <div class="container">
    <el-row class="mb10">
      <el-col :span="16">
        <div class="flex">
          <!-- <el-select v-model="belongingUnit" placeholder="请选择单位" clearable>
            <el-option :label="el.name" :value="el.id" :key="k" v-for="(el, k) in options"  />
          </el-select> -->
          <div class="conUnitName">
            <el-cascader
              popper-class="gy-cascader"
              :options="options"
              :props="data.popupTreeProps"
              v-model="belongingUnitSearch"
              :show-all-levels="false"
              placeholder="请选择单位"
              clearable>
              <template #default="{ data }">
                <el-tooltip
                 :disabled="data.name.length < 13"
                  class="item"
                  effect="dark"
                  :content="data.name"
                  placement="bottom-start"
                >
                  <span>{{ data.name }}</span>
                </el-tooltip>
              </template>
            </el-cascader>
          </div>
          <el-select v-model="budgetYear" placeholder="请选择年份" clearable>
            <el-option :label="el.name" :value="el.value" :key="k" v-for="(el, k) in budgetYearlist1"  />
          </el-select>
          <el-button color="#626aef" @click="getListData" class="ordinary">搜索</el-button>
        </div>
      </el-col>
      <el-col :span="8" align="right">
        <el-button class="ordinary" @click="getExportBtn" v-limit="'YSGL:KYJFYS:EXPERT'">批量导出</el-button>
        <el-button type="danger" @click="deleteList" v-limit="'YSGL:KYJFYS:DELETE'">批量删除</el-button>
        <el-button type="primary" @click="add" v-limit="'YSGL:KYJFYS:ADD'">新增</el-button>
      </el-col>
    </el-row>
    <el-table :data="allTableData" style="width: 100%"  @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column label="序号" type="index" :index="indexMethod" width="50" />
      <el-table-column :prop="el.type" :label="el.label" :key="k" v-for="(el, k) in columns" />
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }"  >
          <el-button   class="ordinary"  @click="handleEdit(row)" v-limit="'YSGL:KYJFYS:EDIT'">编辑</el-button>
          <el-button  @click="openMonthTable(row)"  class="ordinary"  v-limit="'YSGL:KYJFYS:MONTHAPPLY'">月度申报</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="tc mt15">
      <el-pagination background
                     layout="prev, pager, next ,total,sizes,jumper"
                     :total="page.total"
                     :page-size="page.pageSize"
                     :current-page="page.page"
                     @current-change="(e: number) => {
                       page.page = e;
                       getListData()
                     }"
                     @size-change="(e: number) => {
                       page.pageSize = e;
                       getListData()
                     }" />
    </div>

    <el-dialog v-model="data.dialogVisible" width="670px" :show-close="false" :close-on-click-modal="false" @close="close1">
      <template #title>
        <div class="my-header">
          <el-tabs v-model="activeName" class="demo-tabs">
            <el-tab-pane label="基本信息" name="first"></el-tab-pane>
          </el-tabs>
        </div>
      </template>
      <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm" status-icon>
        <!--        <el-form-item label="单位" prop="belongingUnit"  >
              <popup-tree-input
                  :data="options" :disabled="data.addFlag == 1"
                  :props="data.popupTreeProps"
                  :prop="
                  deptForm.parentName == null
                  ? $t('message.org.top_menu')
                  : ruleForm.belongingUnitName
                  "
                  :node-key="'' + deptForm.parentId"
                  :current-change-handle="changeValue8"
                  />
                          <el-form-item label="年份" prop="budgetYear">
          <el-select v-model="ruleForm.budgetYear" placeholder="请选择" style="width: 500px" :disabled="data.addFlag == 1">
            <el-option :label="el.name" :value="el.value" :key="k" v-for="(el, k) in budgetYearlist" />
          </el-select>
        </el-form-item>
                  -->
          <el-form-item label="单位" prop="belongingUnit"  >
          <popup-tree-input
          :data="options"
          :props="data.popupTreeProps"
          :prop="
          deptForm.parentName == null
          ? $t('message.org.top_menu')
          : ruleForm.belongingUnitName
          "
          :node-key="'' + deptForm.parentId"
          :current-change-handle="changeValue8"
          />
        </el-form-item>
        <el-form-item label="年份" prop="budgetYear">
          <el-select v-model="ruleForm.budgetYear" placeholder="请选择" style="width: 500px" >
            <el-option :label="el.name" :value="el.value" :key="k" v-for="(el, k) in budgetYearlist" />
          </el-select>
        </el-form-item>
        <el-form-item label="总预算(万元)" prop="budgetAmount">
<!--          <el-input placeholder="请输入" v-model.number="ruleForm.budgetAmount" style="width: 500px" />-->
          <el-input placeholder="请输入" v-model="ruleForm.budgetAmount" style="width: 500px"
                    maxlength="12"
                    oninput="value=value.replace(/[^\d.]/g, '')
                    .replace(/\.{2,}/g, '.').replace('.', '$#$')
                    .replace(/\./g, '')
                    .replace('$#$', '.')
                    .replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3')
                    .replace(/^\./g, '')"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.dialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="sure">保存</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 月度 -->
    <el-dialog v-model="monthVisible.isShow" width="60%"  style="" :show-close="false" :close-on-click-modal="false">
      <template #title>
        <div class="open-title">{{ ruleForm.budgetYear }}年-中咨集团{{ ruleForm.belongingUnitName }}</div>
      </template>
      <el-table :data="openTableData" style="width: 100%;height:620px" border>
        <el-table-column prop="dataBasedMonth" label="月份" />
        <el-table-column prop="actualAmount" label="月度金额（万元）">
          <template #default="{ row }">
<!--            <el-input v-model.number="row.actualAmount" v-if="row.isEdit" placeholder="请填写" type="number"-->
            <el-input v-model="row.actualAmount" v-if="row.isEdit" placeholder="请填写"
                      oninput="value=value.replace(/[^\d.]{0,14}/g, '')
                      .replace(/\.{2,}/g, '.')
                      .replace('.', '$#$').replace(/\./g, '')
                      .replace('$#$', '.')
                      .replace( /^1\d{10}$/, '.')
                      .replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3')
                      .replace(/^\./g, '')"  />
<!--            <el-input v-model="row.actualAmount" v-if="row.isEdit" placeholder="请填写"
             oninput="value=value.replace(/^\d{0,12}(\.\d{0,2})?$/)" maxlength="14" />-->
            <span v-else>{{ row.actualAmount }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button v-if="!scope.row.isEdit" size="small" type="text" color="primary"
              @click="handleEditItem(scope.row)">编辑</el-button>
            <div v-else>
              <el-button size="small" type="text" color="#f40" @click="cancelItem(scope.row)">取消</el-button>
              <el-button size="small" type="text" color="success" @click="saveItem(scope.row)">保存</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="monthVisible.isShow = false ;ruleForm.belongingUnit = '';
      ruleForm.belongingUnitName = ''">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts">
import * as proxy from "@/constants/proxy";
import request from "@/utils/request";
import PopupTreeInput from '@/views/science/components/PopupTreeInput/index.vue';
import { Modals } from "@/views/science/components/tips/tips";
import { ElMessage, ElMessageBox } from 'element-plus';
import { ObjectType } from 'typings/interfaces';
import { onMounted, reactive, ref } from 'vue';
import {
deleteAll,
getExport,
getList,
insert,
monthReportUpdate,
selectItemOpen,
update
} from '../../api/research';
export default {
  components: {PopupTreeInput},
  setup() {
    const activeName = ref('first')

    // const budgetYear = ref('2023')
    const budgetYear = ref('')
    let data = reactive({
      dialogVisible: false,
      addFlag: 0,
      popupTreeProps: {
        label: 'name',
        children: 'children',
        value:'id',
        checkStrictly: true,
      },
    })
    let loading = ref(true)
    // 列表
    let allTableData = ref([])
    const page = {
      page: 1,
      pageSize: 10,
      total: 0,
    }
    interface Config {
      id: string
    }
    let selectArr: Config[] = reactive([])
    const handleSelectionChange = (val) => {
      selectArr = val
      console.log(val, selectArr)
    }
    let getListData = () => {
      selectArr = []
      loading.value = true
      getList({
        page: page.page,
        pageSize: page.pageSize,
        belongingUnit: belongingUnitSearch.value ?  belongingUnitSearch.value[belongingUnitSearch.value.length - 1] : '',
        budgetYear: budgetYear.value,
      })
        .then((res) => {
          let resData = res.data.data
          allTableData.value = resData.records
          page.total = resData.total
          console.log(allTableData, page, '++', res)
        })
        .finally(() => {
          loading.value = false
        })
    }
    let options = ref([])
    const belongingUnitSearch = ref([])
    // 先获取单位下拉框，然后加载列表
    // getOrgInfo()
    //   .then((res) => {
    //     let arr = res.data?.data || []
    //     options.value = arr
    //     console.log(options, '++++')
    //   })
    //   .finally(() => {
    //     getListData()
    //   })
    const getOrgList = () =>{
      return request({
        url: proxy.CHECC_API_CMS + "/org/getSysOrgList",
        method: "get",
      }).then(res =>{
        options.value = res.data.data
      })
    }

    // 批量删除
    const deleteList = () => {
      ElMessageBox.confirm('确定要删除选中数据吗?', '提示', {
        type: 'warning',
      }).then(() => {
        loading.value = true;
        if (selectArr.length !== 0) {
          deleteAll({
            id: selectArr
                .map((el) => {
                  return el.id
                })
                .join(','),
          }).then((res) => {
            if (res.data.code == 200) ElMessage.success('删除成功')
            getListData()
          })
        } else {
          ElMessage({
            message: '请选择数据后删除！',
            type: 'warning',
          })
        }
      }).catch(() => {
        ElMessage({
          message: '取消了删除！',
          type: 'warning',
        })
        getListData()
        console.log('点击了取消');
      });
    }

    let selectedRows: ObjectType[] = []
    let columns = [
      {
        key: 'date',
        type: 'budgetYear',
        width: 140,
        label: '年度',
      },
      {
        key: 'units',
        type: 'belongingUnitName',
        width: 140,
        label: '单位',
      },
      {
        key: 'estimated',
        type: 'budgetAmount',
        width: 140,
        label: '预计投入金额（万元）',
      },
      {
        key: 'actual',
        type: 'actualAmount',
        width: 140,
        label: '实际投入金额（万元）',
      },
      {
        key: 'annual',
        type: 'rate',
        width: 140,
        label: '占全年比例',
      },
    ]
    const deptForm = {
      parentId: 0,
      parentName: '',
    }
    const budgetYearlist = [
      {
        value: '2020',
        name: '2020',
      },
      {
        value: '2021',
        name: '2021',
      },
      {
        value: '2022',
        name: '2022',
      },
      {
        value: '2023',
        name: '2023',
      },
      {
        value: '2024',
        name: '2024',
      },
      {
        value: '2025',
        name: '2025',
      },
    ]

    const budgetYearlist1 = [
      {
        value: '',
        name: '全部',
      },
      {
        value: '2020',
        name: '2020',
      },
      {
        value: '2021',
        name: '2021',
      },
      {
        value: '2022',
        name: '2022',
      },
      {
        value: '2023',
        name: '2023',
      },
      {
        value: '2024',
        name: '2024',
      },
      {
        value: '2025',
        name: '2025',
      },
    ]
    const ruleForm = reactive({
      budgetYear: '',
      budgetAmount: 0,
      belongingUnit: '',
      belongingUnitName: '',
      id: ''
    })
    const indexMethod = (index)=>{
      return page.pageSize*(page.page-1) +index+1
    }
    const handleEdit = (row) => {
      console.log(row)
      data.dialogVisible = true
      ruleForm.budgetYear = row.budgetYear
      ruleForm.budgetAmount = +row.budgetAmount
      ruleForm.belongingUnit = row.belongingUnit
      ruleForm.belongingUnitName = row.belongingUnitName
      ruleForm.id = row.id
      data.addFlag = 1
    }

    // 新增
    const rules = reactive({
      budgetAmount: [
        { required: true, message: '请输入数字', trigger: 'blur' },
        // { type: 'number', message: '请输入数字' },
      ],
      budgetYear: [
        {
          required: true,
          message: '请选择',
          trigger: 'change',
        },
      ],
      belongingUnit: [
        {
          required: true,
          message: '请选择',
          trigger: 'change',
        },
      ],
    })

    let getExportBtn = () => {
      Modals("是否导出全部数据", "提示", "warning")
        .then(async () => {
          console.log("点击了qr");
          await getExport({
            belongingUnit: belongingUnitSearch.value[belongingUnitSearch.value.length - 1],
             budgetYear: budgetYear.value,
             ids: selectArr
                .map((el) => {
                  return el.id
                })

          }, "科研经费预算");
        })
        .catch(() => {
          console.log("点击了取消");
        });
    };

    const add = () => {
      ruleForm.budgetYear = ''
      ruleForm.budgetAmount = 0
      ruleForm.belongingUnit = ''
      data.dialogVisible = true
      data.addFlag = 0
    }
    const ruleFormRef = ref()
    const sure = async () => {
      console.log(ruleForm.budgetYear, ruleForm.budgetAmount, ruleForm.belongingUnit.trim())
      if (data.addFlag == 1) {
        await ruleFormRef.value.validate((valid, fields) => {
          if (valid) {
            update({
              budgetYear: ruleForm.budgetYear,
              budgetAmount: ruleForm.budgetAmount,
              belongingUnit: ruleForm.belongingUnit.trim(),
              id: ruleForm.id
            }).then((res) => {
              getListData()
              data.dialogVisible = false
              return ElMessage.success({
                message: '操作成功',
                type: 'success',
              })

            })
          }
        })
      } else {
        await ruleFormRef.value.validate((valid, fields) => {
          if (valid) {
            insert({
              budgetYear: ruleForm.budgetYear,
              budgetAmount: ruleForm.budgetAmount,
              belongingUnit: ruleForm.belongingUnit.trim(),
            }).then((res) => {
              getListData()
              data.dialogVisible = false
              return ElMessage({
                message: '操作成功',
                type: 'success',
              })
            })
          }
        })
      }
    }
    // 月度账单
    let monthVisible = reactive({ isShow: false })
    let openTableData = ref([])
    let cur = { belongingUnit: '', budgetYear: '' }
    const getOpenData = () => {
      selectItemOpen({
        belongingUnit: cur.belongingUnit,
        budgetYear: cur.budgetYear,
      }).then((res) => {
        const data = res.data.data;
        openTableData.value = data.map(t => ({ ...t, oldActualAmount: t.actualAmount }));
      })
    }
    const openMonthTable = (row) => {
      cur = row
      monthVisible.isShow = true
      ruleForm.budgetYear = row.budgetYear
      ruleForm.belongingUnitName = row.belongingUnitName
      getOpenData()
    }

    const handleEditItem = (row) => {
      row.isEdit = true
    }
    const cancelItem = (row) => {
      row.actualAmount = row.oldActualAmount;
      row.isEdit = false
    }
    const saveItem = (row) => {
      const actualAmount = row.actualAmount;
      monthReportUpdate({
        belongingUnit: row.belongingUnit,
        dataBasedMonth: row.dataBasedMonth,
        actualAmount,
        id: row.id,
      }).then(() => {
        row.oldActualAmount = actualAmount;
        ruleForm.belongingUnit = '';
        ruleForm.belongingUnitName = '';
        getOpenData()
        getListData()
        ElMessage({
          message: '操作成功',
          type: 'success',
        })
      })
    }
    const changeValue8 = (item) => {
      ruleForm.belongingUnit = item.id
      ruleForm.belongingUnitName = item.name
    }
    let close1 = () =>{
      ruleForm.belongingUnitName = ''
    }
    onMounted(() =>{
      getOrgList()
      getListData()
    })
    return {
      getExportBtn,
      activeName,
      close1,
      belongingUnitSearch,
      budgetYear,
      options,
      data,
      allTableData,
      budgetYearlist,
      page,
      selectedRows,
      columns,
      handleEdit,
      // 列表
      getListData,
      handleSelectionChange,
      // 新增
      add,
      sure,
      ruleForm,
      rules,
      ruleFormRef,
      deleteList,
      selectArr,
      indexMethod,
      monthVisible,
      openMonthTable,
      openTableData,
      handleEditItem,
      cancelItem,
      saveItem,
      budgetYearlist1,
      deptForm,
      changeValue8,
    }
  },
}
</script>
<style lang="scss">
.conUnitName{
    display: inline-block;
    width: 200px;
    margin-right: 15px;
}
.gy-cascader{
  .el-cascader-node {
    max-width: 250px;
  }
}
</style>
<style lang="scss" scoped>
.container {
  background-color: white;
  padding: 20px;
}

.el-col {
  line-height: 40px;
}

.el-form-item {
  .el-input {
    width: 100px;
    background-color: aliceblue;
  }

  .el-select {
    width: 100px;
  }
}

.custom-color {
  color: red !important;
  /* 确保优先级高于其他样式 */
}

.el-table th {
  background-color: #f0f0f0;
  /* 修改表头背景色 */
  color: #333;
  /* 修改表头文字颜色 */
}

/* .demo-tabs > .el-tabs__content {
  padding: 32px;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
} */

.open-title {
  font-size: 20px;
  font-weight: 700;
  text-align: center;
}

/deep/.el-dialog__body {
  display: block !important;
}

.mt15 {
  margin-top: 15px;
}

.mb10 {
  margin-bottom: 10px;
}

.tc {
  text-align: center;
}
.el-dialog__body {
  padding: calc(var(--el-dialog-padding-primary) + -20px) var(--el-dialog-padding-primary);
  /* color: var(--el-text-color-regular); */
  /* font-size: var(--el-dialog-content-font-size); */
  word-break: break-all;
}
</style>
